package com.javasm.boot.oauth2.handler;

import com.javasm.boot.oauth2.entity.Response;
import com.javasm.boot.oauth2.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Author：MoDebing
 * Version：1.0
 * Date：2022-12-13-15:20
 * Description:
 */

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Component
public class MyExceptionHandler {

    @Autowired
    private WebUtils webUtils;

    //@ExceptionHandler注解中可以添加参数，
    //参数是某个异常类的class，代表这个方法专门处理该类异常，比如这样：
    @ExceptionHandler(Exception.class)
    public void myExceptionHandler(Exception ex) {
        Response response = null;
        ex.printStackTrace();
        if (ex instanceof InvalidTokenException){
            response = new Response().msg("token已过期，details:" + ex.getMessage()).code(HttpStatus.UNAUTHORIZED);
        }else if (ex instanceof AccessDeniedException){
            response = new Response().msg("未授权，details:"+ex.getMessage()).code(HttpStatus.FORBIDDEN);
        }else if (ex instanceof AuthenticationException){
            response = new Response().msg("未认证，details:"+ex.getMessage()).code(HttpStatus.UNAUTHORIZED);
        }else {
            response = new Response().msg("错误请求,details:"+ex.getMessage()).code(HttpStatus.BAD_REQUEST);
        }
        webUtils.renderString(response);
    }

}
